package com.example.mytestdemo.custom

import android.util.Log
import android.view.View
import androidx.camera.core.CameraControl
import androidx.camera.core.FocusMeteringAction
import androidx.camera.core.MeteringPointFactory
import androidx.camera.core.SurfaceOrientedMeteringPointFactory
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit


/**
 * created tsts
 * 2023/11/4
 *
 */
class AutoFocusHelper(
        private val lifecycleOwner: LifecycleOwner,
        private val mCameraControl: CameraControl?,
        private val cameraPreviewView: View
) {

    private var autoFocusX: Int
    private var autoFocusY: Int
    private var job: Job? = null

    init {
        val outLocation = IntArray(2)
        cameraPreviewView.getLocationInWindow(outLocation)

        val width = cameraPreviewView.width
        val height = cameraPreviewView.height

        autoFocusX = outLocation[0] + cameraPreviewView.width / 2
        autoFocusY = outLocation[1] + cameraPreviewView.height / 2

        Log.e("tag-ugc", "width = $width   height = $height")
        Log.e("tag-ugc", "autoFocusX = $autoFocusX    autoFocusY = $autoFocusY")
    }

    /**
     * 自动聚焦
     */
    private fun autoFocus(x: Int, y: Int) {
        if (x == 0 || y == 0) return
//        MeteringPointFactory factory = previewView.getMeteringPointFactory();
        val factory: MeteringPointFactory = SurfaceOrientedMeteringPointFactory(x.toFloat(), y.toFloat())
        val point = factory.createPoint(x.toFloat(), y.toFloat())
        val action = FocusMeteringAction.Builder(point, FocusMeteringAction.FLAG_AF)
            // 3秒内自动调用取消对焦
            .setAutoCancelDuration(3, TimeUnit.SECONDS)
            .build()
        //mCameraControl.cancelFocusAndMetering();
        val future = mCameraControl?.startFocusAndMetering(action)
//        future?.addListener({
//            try {
//                if (future.get().isFocusSuccessful) {
//                    //聚焦成功
//                    Log.e("TAG", "聚焦成功")
//                } else {
//                    //聚焦失败
//                    Log.e("TAG", "聚焦失败")
//                }
//            } catch (e: Exception) {
//                Log.e("TAG", "聚焦异常" + e.message)
//            }
//
//        }, ContextCompat.getMainExecutor(cameraPreviewView.context))
    }

    fun autoFocusTimer() {
        autoFocusCancel()
        job = lifecycleOwner.lifecycleScope.launch {
            while (isActive) {
                delay(3000)
                autoFocus(autoFocusX, autoFocusY)
            }
        }
    }

    fun autoFocusCancel() {
        job?.cancel()
    }

}